# for plotting errbar
from htstool.models import *
from matplotlib import pyplot as plt
import numpy as np
import pandas as pd

class Errbar():

	# 1 - irrad 2 - nonrad
	def pl_means_vs_nt_means(self, plates1, plates2, NT):
		pl1_stds, pl1_means, NT_std1s, NT_mean1s, pl2_stds, pl2_means, NT_std2s, NT_mean2s = self._getmeans(plates1, NT) + self._getmeans(plates2, NT)
		self.draw_err(pl1_stds, pl1_means, NT_std1s, NT_mean1s, pl2_stds, pl2_means, NT_std2s, NT_mean2s)	
	
	# NT are neg control labels [('A', '02'), ('B', '02')]
	def _getmeans(self, plates, NT):
		NT_means=[]
		NT_stds=[]
		pl_means=[]
		pl_stds=[]
		for p in plates:
			df=p.data.dataframe
			if len(NT)!=0:
				nt_vals=[df.loc[nt] for nt in NT ]
									
			ser_nt=pd.Series(nt_vals)
			NT_means.append(ser_nt.values.mean())	
			NT_stds.append(ser_nt.values.std())	
			pl_means.append(df.values.mean())	
			pl_stds.append(df.values.std())	
		return [ pl_stds, pl_means, NT_stds , NT_means]

	
	def draw_err(self, pl1_stds, pl1_means, NT_std1s, NT_mean1s, pl2_stds, pl2_means, NT_std2s, NT_mean2s):

		err1=np.array(pl1_stds+pl2_stds)
		err2=np.array(NT_std1s+NT_std2s)
		
		fig1=plt.figure()
		c1=['r']*len(pl1_means)
		c2=['black']*len(pl1_means)
		plt.errorbar(pl1_means+pl2_means, NT_mean1s+NT_mean2s, xerr=err1, yerr=err2, fmt=None, zorder=1)
		plt.scatter(pl1_means+pl2_means, NT_mean1s+NT_mean2s, c=c1+c2,  edgecolor='none', zorder=10)
		plt.title("Plate mean vs NT mean")

		xma=np.max(pl1_means+pl2_means)
		xmi=np.min(pl1_means+pl2_means)
		yma=np.max(NT_mean1s+NT_mean2s)
		ymi=np.min(NT_mean1s+NT_mean2s)

		xlim=[xmi-err1.max()-xmi/10, xma+err1.max()+xmi/10]
		ylim=[ymi-err2.max()-ymi/10, yma+err2.max()+ymi/10]
		
		xanno=xmi-err1.max()
		yanno=yma
		plt.annotate('irradiated', xy=(xanno, yanno),
			    xytext=(35, 0), textcoords='offset points', size=10, va="center",
			    bbox=dict(boxstyle="round", fc=(1.0, 0.7, 0.7), ec="none"),
			    arrowprops=dict(arrowstyle="wedge,tail_width=1.",
				fc=(1.0, 0.7, 0.7), ec="none",
				relpos=(0.2, 0.5),
			   ))
		plt.annotate('non-radiated', xy=(xanno, yanno*.96),
			    xytext=(35, 0), textcoords='offset points', size=10, va="center",
			    bbox=dict(boxstyle="round", fc=(1.0, 0.7, 0.7), ec="none"),
			    arrowprops=dict(arrowstyle="wedge,tail_width=1.",
				fc=(1.0, 0.7, 0.7), ec="none",
				relpos=(0.2, 0.5),
			   ))
		
		plt.scatter((xanno, xanno), (yanno*.96, yanno), c=['black', 'r'], edgecolor='none')
		plt.plot((0,ylim[1]), (0,ylim[1]), '-'); plt.grid()
		plt.xlim(xlim)
		plt.ylim(ylim)
		plt.xlabel('means of the plates')
		plt.ylabel('negative control means')
		
		fig1.savefig('errbar.pdf')


if __name__=='__main__':

	nonrad_g = PlateGroup.objects.get(groupname='RAW readout non-radiated plates')
	nonrad_plates = nonrad_g.plates[20:]
	#nonrad_plates = nonrad_g.plates[:20]
	irrad_g = PlateGroup.objects.get(groupname='RAW readout irradiated plates')
	irrad_plates = irrad_g.plates[20:]
	#irrad_plates = irrad_g.plates[:20]

	form = Errbar()
	
	# negative control for RKO-T29
	#NT=[('C', '02'), ('D', '02'), ('G', '02'), ('H', '02'), ('K', '02'), ('L', '02'), ('O', '02'), ('P', '02'), 
	#	('C', '23'), ('D', '23'), ('G', '23'), ('H', '23'), ('K', '23'), ('L', '23'), ('O', '23'), ('P', '23')]
	
	# negative control for the rest plates
	NT=[('C', '02'), ('D', '02'), ('G', '02'), ('H', '02'), ('K', '02'), ('L', '02'), ('O', '02'), ('P', '02'), 
		('A', '02'), ('B', '02'), ('E', '02'), ('F', '02'), ('I', '02'), ('J', '02'), ('M', '02'), ('N', '02'), 
		('J', '22'), ('L', '22'), ('N', '22'), ('P', '22'), ('M', '23'), ('N', '23'), ('O', '23'), ('P', '23'),
		('J', '21'), ('L', '21'), ('N', '21'), ('P', '21'), ('H', '21'), ('F', '21'), ('D', '21'), ('B', '21'),
		('J', '19'), ('L', '19'), ('N', '19'), ('P', '19'), ('H', '19'), ('F', '19'), ('D', '19'), ('B', '19'),
		('N', '17'), ('P', '17')]

	form.pl_means_vs_nt_means(irrad_plates, nonrad_plates, NT)

